/**
 * 测试LangChain修复后的功能
 */

const http = require('http');

// 测试基本聊天
function testBasicChat() {
  return new Promise((resolve, reject) => {
    const postData = JSON.stringify({
      messages: [{ role: 'user', content: '你好' }],
      userId: 'test-user'
    });

    const options = {
      hostname: 'localhost',
      port: 5000,
      path: '/api/chat-langchain/chat',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      }
    };

    const req = http.request(options, (res) => {
      let data = '';
      res.on('data', (chunk) => {
        data += chunk;
      });
      res.on('end', () => {
        try {
          const result = JSON.parse(data);
          console.log('✅ 基本聊天测试成功');
          console.log('AI回复:', result.data?.content || '无内容');
          resolve(result);
        } catch (error) {
          console.log('❌ 解析响应失败:', error.message);
          reject(error);
        }
      });
    });

    req.on('error', (error) => {
      console.log('❌ 请求失败:', error.message);
      reject(error);
    });

    req.write(postData);
    req.end();
  });
}

// 测试工具调用
function testToolCall() {
  return new Promise((resolve, reject) => {
    const postData = JSON.stringify({
      messages: [{ role: 'user', content: '查询所有任务' }],
      userId: 'test-user'
    });

    const options = {
      hostname: 'localhost',
      port: 5000,
      path: '/api/chat-langchain/chat',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      }
    };

    const req = http.request(options, (res) => {
      let data = '';
      res.on('data', (chunk) => {
        data += chunk;
      });
      res.on('end', () => {
        try {
          const result = JSON.parse(data);
          console.log('✅ 工具调用测试成功');
          console.log('AI回复:', result.data?.content || '无内容');
          if (result.data?.tool_calls && result.data.tool_calls.length > 0) {
            console.log('工具调用:', result.data.tool_calls);
          }
          if (result.data?.tool_results && result.data.tool_results.length > 0) {
            console.log('工具结果:', result.data.tool_results);
          }
          resolve(result);
        } catch (error) {
          console.log('❌ 解析响应失败:', error.message);
          reject(error);
        }
      });
    });

    req.on('error', (error) => {
      console.log('❌ 请求失败:', error.message);
      reject(error);
    });

    req.write(postData);
    req.end();
  });
}

// 运行测试
async function runTests() {
  console.log('🚀 开始测试LangChain修复...\n');
  
  try {
    await testBasicChat();
    console.log('');
    await testToolCall();
    console.log('\n✨ 测试完成！');
  } catch (error) {
    console.log('\n❌ 测试失败:', error.message);
  }
}

runTests();
